#!/bin/bash

# 图生图API自动部署脚本
# 适用于Ubuntu/Debian系统

set -e

echo "🚀 开始自动部署图生图API服务..."

# 检测系统
if [[ -f /etc/os-release ]]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
else
    echo "❌ 无法检测系统版本"
    exit 1
fi

echo "检测到系统: $OS $VER"

# 更新系统
echo "📦 更新系统包..."
if [[ $OS == *"Ubuntu"* ]] || [[ $OS == *"Debian"* ]]; then
    sudo apt update && sudo apt upgrade -y
    sudo apt install -y python3 python3-pip python3-venv nginx git curl
elif [[ $OS == *"CentOS"* ]] || [[ $OS == *"Red Hat"* ]]; then
    sudo dnf update -y
    sudo dnf install -y python3 python3-pip nginx git curl
else
    echo "❌ 不支持的系统: $OS"
    exit 1
fi

# 创建用户和目录
echo "👤 创建服务用户..."
sudo useradd -r -s /bin/false imageapi || true
sudo mkdir -p /opt/image-gen-api
sudo chown imageapi:imageapi /opt/image-gen-api

# 切换到项目目录
cd /opt/image-gen-api

# 如果是从git克隆，取消注释下面的行
# git clone https://github.com/your-repo/image-gen-api.git .

echo "📁 请确保项目文件已上传到 /opt/image-gen-api"
echo "按任意键继续..."
read -n 1

# 创建虚拟环境
echo "🐍 创建Python虚拟环境..."
sudo -u imageapi python3 -m venv venv
sudo -u imageapi ./venv/bin/pip install --upgrade pip

# 安装依赖
echo "📦 安装Python依赖..."
sudo -u imageapi ./venv/bin/pip install -r requirements.txt

# 配置环境变量
echo "⚙️ 配置环境变量..."
if [[ ! -f .env ]]; then
    sudo -u imageapi cp .env.production .env
    echo "请编辑 /opt/image-gen-api/.env 文件，填入您的Gemini API密钥"
    echo "GEMINI_API_KEY=your_api_key_here"
    echo "按任意键继续..."
    read -n 1
fi

# 创建日志目录
sudo -u imageapi mkdir -p logs uploads

# 生成systemd服务文件
echo "🔧 配置systemd服务..."
cat > /tmp/image-gen-api.service << EOF
[Unit]
Description=图生图转接API服务
After=network.target

[Service]
Type=simple
User=imageapi
Group=imageapi
WorkingDirectory=/opt/image-gen-api
Environment=PATH=/opt/image-gen-api/venv/bin
ExecStart=/opt/image-gen-api/venv/bin/python -m gunicorn -w 4 -b 127.0.0.1:5000 --timeout 120 app:create_app()
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

sudo mv /tmp/image-gen-api.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable image-gen-api

# 配置Nginx
echo "🌐 配置Nginx..."
cat > /tmp/image-gen-api-nginx << EOF
server {
    listen 80;
    server_name _;

    client_max_body_size 20M;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    access_log /var/log/nginx/image-gen-api.access.log;
    error_log /var/log/nginx/image-gen-api.error.log;
}
EOF

sudo mv /tmp/image-gen-api-nginx /etc/nginx/sites-available/image-gen-api
sudo ln -sf /etc/nginx/sites-available/image-gen-api /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default

# 测试Nginx配置
sudo nginx -t

# 启动服务
echo "🚀 启动服务..."
sudo systemctl start image-gen-api
sudo systemctl reload nginx

# 检查服务状态
echo "📊 检查服务状态..."
sleep 3
sudo systemctl status image-gen-api --no-pager

# 测试API
echo "🔍 测试API..."
sleep 2
if curl -f http://localhost/health > /dev/null 2>&1; then
    echo "✅ API服务正常运行"
else
    echo "❌ API服务可能有问题，请检查日志"
    sudo journalctl -u image-gen-api --no-pager -n 20
fi

# 配置防火墙
echo "🔒 配置防火墙..."
if command -v ufw > /dev/null; then
    sudo ufw allow 80
    sudo ufw allow 443
    sudo ufw --force enable
elif command -v firewall-cmd > /dev/null; then
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
fi

echo ""
echo "🎉 部署完成！"
echo "================================"
echo "服务状态: sudo systemctl status image-gen-api"
echo "查看日志: sudo journalctl -u image-gen-api -f"
echo "重启服务: sudo systemctl restart image-gen-api"
echo "API地址: http://your-server-ip/"
echo "API文档: http://your-server-ip/api/v1/docs"
echo ""
echo "⚠️  重要提醒:"
echo "1. 请确保已在 /opt/image-gen-api/.env 中配置正确的API密钥"
echo "2. 如需HTTPS，请配置SSL证书"
echo "3. 建议设置域名解析"
echo "================================"
